package com.company.regist.dao;


import com.company.regist.pojo.Fridends;
import com.company.regist.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class FriendsDAOImpl implements IFriendsDAO {

	@Override
	public int insert(Fridends f) throws SQLException {
		String sql="insert into friends values(null,?,?,?,?)";


		Connection conn= JDBCUtils.getConnection();
		PreparedStatement stmt=conn.prepareStatement(sql);
		stmt.setString(1,f.getTittle());
		stmt.setString(2,f.getText());
		stmt.setString(3,f.getTime());
		stmt.setString(4,f.getUserId());


		int result;
		try{
			result=stmt.executeUpdate();
		}
		catch (SQLException throwables) {
			throwables.printStackTrace();
			result=-1;
		}
		System.out.println("影响行数"+result);
		JDBCUtils.destory(conn,stmt,null);
	return result;
}

	@Override
	public List showFriend() throws SQLException {
		String sql = "select * from friends";
		// 1. 得到连接
		Connection conn = JDBCUtils.getConnection();
		// 2. 创建查询对象
		PreparedStatement stmt = conn.prepareStatement(sql);
		// 3. 执行
		ResultSet rs = stmt.executeQuery();
		List <Fridends> list=new ArrayList<>();
		while(rs.next())
		{
			int id = rs.getInt(1);
			String tittle = rs.getString(2);
			String text = rs.getString(3);
			String time = rs.getString(4);
			String userId = rs.getString(5);
			Fridends f = new Fridends(id,tittle,text,time,userId);
			list.add(f);
		}

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);

		return list;
	}

	@Override
	public int deleteById(int id) throws SQLException {

			System.out.println(id);
			String sql="delete from friends  where id =? ";
			Connection conn=JDBCUtils.getConnection();

			PreparedStatement stmt=conn.prepareStatement(sql);
			stmt.setInt(1,id);

			int result=-1;
			try{
				result=stmt.executeUpdate();
			}
			catch (Exception e)
			{
				System.out.println(e);
				result=-1;
			}
			System.out.println("影响行数"+result);

			JDBCUtils.destory(conn,stmt,null);
			return result;

	}
}

